package com.kingyun.gpsinspection.purificationservice.services.tdm.innerservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.*;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EmployeeVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.*;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.WorkOrderService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * Created by liyi on 2016/12/2.
 */
public class WorkOrderServiceImpl implements WorkOrderService {
    @Autowired
    public TdmWorkOrderMapper tdmWorkOrderMapper;
    @Autowired
    public WorkOrderEmployeeMapper workOrderEmployeeMapper;
    @Autowired
    private CustomWorkCriteriaMapper customWorkCriteriaMapper;
    @Autowired
    private PatrolInspectionMapper patrolInspectionMapper;
    @Autowired
    private MaintenanceMapper maintenanceMapper;

    /**
     * 查看
     *
     * @param workOrder
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> listMap(WorkOrder workOrder) throws Exception {
        Map<String, Object> map = new HashMap<>();
        workOrder.setLimit(workOrder.getLimit() == null ? 10 : workOrder.getLimit());
        workOrder.setOffset(workOrder.getOffset() == null ? 0 : workOrder.getOffset());
        map.put("total", tdmWorkOrderMapper.queryCount(workOrder));
        map.put("rows", tdmWorkOrderMapper.queryList(workOrder));
        return map;
    }

    /**
     * 展示确认工单table数据
     *
     * @param workOrderVo
     * @return
     */
    @Override
    public Map<String, Object> listConfirmMap(WorkOrderVo workOrderVo) throws Exception {
        Map<String, Object> map = new HashMap<>();
        workOrderVo.setLimit(workOrderVo.getLimit() == null ? 10 : workOrderVo.getLimit());
        workOrderVo.setOffset(workOrderVo.getOffset() == null ? 0 : workOrderVo.getOffset());
        map.put("total", tdmWorkOrderMapper.queryConfirmCount(workOrderVo));
        map.put("rows", tdmWorkOrderMapper.queryConfirmList(workOrderVo));
        return map;
    }

    /**
     * 新增
     *
     * @param workOrder
     */
    @Override
    public void saveWorkOrder(WorkOrder workOrder) {
        tdmWorkOrderMapper.insertSelective(workOrder);
    }

    /**
     * 根据任务环节和工单信息保存工单和工单人员关系表：任何步骤都可以修改工单；先删除旧的后新增新的
     *
     * @param employeeVo
     * @param taskId        任务id
     * @param taskType      任务类型
     * @param workOrderList
     * @return
     */
    @Override
    public int saveWorkOrderList(EmployeeVo employeeVo, String taskId, Short taskType, List<WorkOrderVo> workOrderList) {
        if (workOrderList != null && workOrderList.size() > 0) {
            //注意思路：先删除后新增
            List<WorkOrder> oldWorkOrderList = tdmWorkOrderMapper.findListByTaskId(taskId);
            //先根据工单Id删除工单和人员的关系表
            if (oldWorkOrderList != null && oldWorkOrderList.size() > 0) {
                for (WorkOrder oldWorkOrder : oldWorkOrderList) {
                    if (oldWorkOrder != null && oldWorkOrder.getWorkOrderId() != null) {
                        workOrderEmployeeMapper.deleteByWorkOrderId(oldWorkOrder.getWorkOrderId());
                    }
                }
            }

            //再根据任务Id删除该任务对应的工单：
            tdmWorkOrderMapper.deleteByTaskId(taskId);

            //重要方法：给List中的元素回设置
            for (WorkOrderVo workOrder : workOrderList) {
                //重新设置主键ID
                workOrder.setWorkOrderId(UniqueUtil.uuid());
                //关键：必须达到任务ID
                workOrder.setTaskId(taskId);
                //关键：必须拿到任务类型
                workOrder.setTaskType(taskType);
                workOrder.setCreateUserId(employeeVo.getEmployeeId());
                workOrder.setModifyUserId(employeeVo.getEmployeeId());
                //工单状态：-1预处理，0创建，1作业条件检查，2作业前准备，3操作申请（关键操作--才会申请），4审核通过，5审核不通过，6已经完成，7已关闭
                workOrder.setStatus((short) -1);
                //1是删除；0是正常
                workOrder.setIsDelete((short) 0);
                //0未下载；已经下载
                workOrder.setIsDownload((short) 0);
                //0无法完成；1可以完成
                workOrder.setCanFinish((short) 1);
                //0未确认；1已经确认
                workOrder.setConfirmStatus((short) 0);

                //先保存工单
                tdmWorkOrderMapper.insertNew(workOrder);

                //保存工单和人员的关系表：
                if (workOrder.getUserId() != null) {
                    String[] array = workOrder.getUserId().split(",");
                    if (array != null && array.length > 0) {
                        for (int i = 0; i < array.length; i++) {
                            if (StringUtils.isNotBlank(array[i])) {
                                WorkOrderEmployee workOrderEmployee = new WorkOrderEmployee();
                                workOrderEmployee.setWorkOrderEmployeeId(UniqueUtil.uuid());
                                workOrderEmployee.setWorkOrderId(workOrder.getWorkOrderId());
                                workOrderEmployee.setEmployeeId(array[i]);
                                workOrderEmployeeMapper.insert(workOrderEmployee);
                            }
                        }
                    }
                }
                //保存自定义巡检
                if (null != workOrder.getRemark() && workOrder.getRemark() != "") {
                    JSONArray jsonArray = JSON.parseArray(workOrder.getRemark());
                    List<CustomWorkCriteria> list = new ArrayList<>();
                    for (Object o : jsonArray) {
                        JSONObject jsonObject = JSON.parseObject(o.toString());
                        CustomWorkCriteria customWorkCriteria = new CustomWorkCriteria();
                        customWorkCriteria.setId(UniqueUtil.uuid());
                        customWorkCriteria.setWorkOrderId(workOrder.getWorkOrderId());
                        customWorkCriteria.setWorkInstanceId(jsonObject.get("workInstanceId").toString());
                        customWorkCriteria.setRankId(Integer.parseInt(jsonObject.get("categoryIndex").toString()));
                        customWorkCriteria.setCategory(jsonObject.get("category").toString());
                        list.add(customWorkCriteria);
                    }
                    if (list != null && list.size() > 0) {
                        customWorkCriteriaMapper.insertByList(list);
                    }
                }
            }
        }
        return 0;
    }


    /**
     * 修改
     *
     * @param employeeVo
     * @param workOrder
     * @return
     */
    @Override
    public int updateByPrimaryKey(EmployeeVo employeeVo, WorkOrder workOrder) {
        workOrder.setModifyUserId(employeeVo.getEmployeeId());
        workOrder.setModifyTime(new Date());
        return tdmWorkOrderMapper.updateByPrimaryKeySelective(workOrder);
    }

    /**
     * 根据ID修改
     *
     * @param employeeVo
     * @param workOrderId
     * @return
     */
    @Override
    public int updateStateByIds(EmployeeVo employeeVo, String workOrderId) {
        WorkOrder workOrder = new WorkOrder();
        workOrder.setWorkOrderId(workOrderId);
        workOrder.setIsDelete((short) 1);
        workOrder.setModifyUserId(employeeVo.getEmployeeId());
        workOrder.setModifyTime(new Date());
        return tdmWorkOrderMapper.updateByPrimaryKeySelective(workOrder);
    }

    /**
     * 根据ID查询
     *
     * @param workOrderId
     * @return
     * @throws Exception
     */
    @Override
    public WorkOrder findWorkOrderById(String workOrderId) throws Exception {
        return tdmWorkOrderMapper.selectByPrimaryKey(workOrderId);
    }

    /**
     * 根据任务发起ID查询工单
     *
     * @param taskId
     * @return
     * @throws Exception
     */
    @Override
    public List<WorkOrder> findByTaskId(String taskId) throws Exception {
        if (StringUtils.isBlank(taskId)) {
            return null;
        }

        return tdmWorkOrderMapper.findListByTaskId(taskId);
    }

    /**
     * 根据任务发起ID查询工单及关联表
     *
     * @param taskId
     * @return
     * @throws Exception
     */
    @Override
    public List<WorkOrderVo> findVoListByTaskId(String taskId) throws Exception {
        if (StringUtils.isBlank(taskId)) {
            return null;
        }

        List<WorkOrderVo> woList = tdmWorkOrderMapper.findVoListByTaskId(taskId);

        //值为null的字段会被过滤去掉：bootstrap-table无法显示
        for (WorkOrderVo workOrderVo : woList) {
            if (null != workOrderVo.getRemark() && !workOrderVo.getRemark().equals("")) {
                JSONArray jsonArray = JSONArray.parseArray(workOrderVo.getRemark());
                String workCriteriaName = null;
                if (null != jsonArray && jsonArray.size() > 0) {
                    for (Object str : jsonArray) {
                        JSONObject jsonObject = JSONObject.parseObject(str.toString());
                        if (null == workCriteriaName || workCriteriaName.equals("")) {
                            workCriteriaName = jsonObject.get("category").toString();
                        } else {
                            workCriteriaName = workCriteriaName + "," + jsonObject.get("category");
                        }
                    }
                }
                if (null != workCriteriaName && !workCriteriaName.equals("")) {
                    workOrderVo.setWorkCriteriaName(workCriteriaName);
                }
            }
            if (workOrderVo.getEntityTypeId() == null) {
                workOrderVo.setEntityTypeId("");
            }
            if (workOrderVo.getEntityId() == null) {
                workOrderVo.setEntityId("");
            }
            if (workOrderVo.getEntityTypeName() == null) {
                workOrderVo.setEntityTypeName("");
            }
            if (workOrderVo.getEntityName() == null) {
                workOrderVo.setEntityName("");
            }
            if (workOrderVo.getCellId() == null) {
                workOrderVo.setCellId("");
            }
            if (workOrderVo.getCellName() == null) {
                workOrderVo.setCellName("");
            }
            if (workOrderVo.getWorkInstanceId() == null) {
                workOrderVo.setWorkInstanceId("");
            }
            if (workOrderVo.getWorkInstanceName() == null) {
                workOrderVo.setWorkInstanceName("");
            }
        }

        return woList;
    }

    /**
     * 获取待办工单总数
     *
     * @param userId 当前登录人id
     */
    @Override
    public JSONArray queryMyTodoWorkOrderCount(String userId) {
        JSONArray jsonArray = new JSONArray();
        WorkOrderVo workOrderVo = new WorkOrderVo();
        workOrderVo.setUserId(userId);
        //查询总条数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("navLabel", "待我处理工单");
        jsonObject.put("count", tdmWorkOrderMapper.queryConfirmCount(workOrderVo));
        jsonArray.add(jsonObject);
        /*返回结果*/
        return jsonArray;
    }

    /**
     * 待删除
     */
    @Override
    public int saveWorkOrderList(EmployeeVo employeeVo, TaskLink taskLink, List<WorkOrderVo> workOrderList) {
        return 0;
    }

    /**
     * 修改主任务工单
     *
     * @param id              主任务id
     * @param employeeVo      登陆人信息
     * @param workOrderVoList 工单列表
     */
    @Override
    public void updateWorkOrder(EmployeeVo employeeVo, String id, List<WorkOrderVo> workOrderVoList, PatrolInspection patrolInspection, Maintenance maintenance) throws Exception {
        String orgId = null;
        //修改主任务信息
        if (null != patrolInspection.getPatrolInspectionId()) {
            orgId = null != patrolInspection.getOrgId() ? patrolInspection.getOrgId() : null;
            patrolInspectionMapper.updateByPrimaryKeySelective(patrolInspection);
        } else if (null != maintenance.getMaintenanceId()) {
            orgId = null != maintenance.getOrgId() ? maintenance.getOrgId() : null;
            maintenanceMapper.updateByPrimaryKeySelective(maintenance);
        }
        //修改所有的工单执行组织
        if (null != orgId && !orgId.equals("")) {
            tdmWorkOrderMapper.updateOrgIdByTaskId(id, orgId);
        }
        //删除所有工单
        tdmWorkOrderMapper.deleteByTaskId(id);
        //插入新工单
        if (workOrderVoList != null && workOrderVoList.size() > 0) {
            //重要方法：给List中的元素回设置
            for (WorkOrderVo workOrder : workOrderVoList) {
                //删除工单所有的审批人
                workOrderEmployeeMapper.deleteByWorkOrderId(workOrder.getWorkOrderId());
                //删除自定义巡检
                customWorkCriteriaMapper.deleteByWorkOrderId(workOrder.getWorkOrderId());
                //重新设置主键ID
                workOrder.setWorkOrderId(UniqueUtil.uuid());
                workOrder.setCreateUserId(employeeVo.getEmployeeId());
                workOrder.setModifyUserId(employeeVo.getEmployeeId());
                //1是删除；0是正常
                workOrder.setIsDelete((short) 0);
                //0未下载；已经下载
                workOrder.setIsDownload((short) 0);
                //0无法完成；1可以完成
                workOrder.setCanFinish((short) 1);
                //0未确认；1已经确认
                workOrder.setConfirmStatus((short) 0);
                workOrder.setCreateTime(new Date());
                workOrder.setModifyTime(new Date());
                //先保存工单
                tdmWorkOrderMapper.insertNew(workOrder);
                //保存工单和人员的关系表：
                if (null != workOrder.getUserId() && !workOrder.getUserId().equals("")) {
                    String[] array = workOrder.getUserId().split(",");
                    if (null != array && array.length > 0) {
                        for (String userId : array) {
                            WorkOrderEmployee workOrderEmployee = new WorkOrderEmployee();
                            workOrderEmployee.setWorkOrderEmployeeId(UniqueUtil.uuid());
                            workOrderEmployee.setWorkOrderId(workOrder.getWorkOrderId());
                            workOrderEmployee.setEmployeeId(userId);
                            workOrderEmployeeMapper.insert(workOrderEmployee);
                        }
                    }
                }
                //保存自定义巡检
                if (null != workOrder.getRemark() && !workOrder.getRemark().equals("")) {
                    JSONArray jsonArray = JSON.parseArray(workOrder.getRemark());
                    List<CustomWorkCriteria> list = new ArrayList<>();
                    for (Object o : jsonArray) {
                        JSONObject jsonObject = JSON.parseObject(o.toString());
                        CustomWorkCriteria customWorkCriteria = new CustomWorkCriteria();
                        customWorkCriteria.setId(UniqueUtil.uuid());
                        customWorkCriteria.setWorkOrderId(workOrder.getWorkOrderId());
                        customWorkCriteria.setWorkInstanceId(jsonObject.get("workInstanceId").toString());
                        customWorkCriteria.setRankId(Integer.parseInt(jsonObject.get("categoryIndex").toString()));
                        customWorkCriteria.setCategory(jsonObject.get("category").toString());
                        list.add(customWorkCriteria);
                    }
                    if (list != null && list.size() > 0) {
                        customWorkCriteriaMapper.insertByList(list);
                    }
                }
            }
        }
    }
}
